import { AuthActionTypes, OAuthStateInterface, OAUTH_SESSION_LOGOUT_TYPE, OAUTH_LOGOUT_TYPE, OAUTH_QQ_USER_INFO_TYPE } from './types'
import { Dispatch } from 'redux'
import { get } from '../../ajax/axios'
import { OAuth } from '../../ajax/api'
import { PublicENV } from '@config/env'
import Cookie from 'js-cookie'

/**
 * session 登录
 */
export function sessionLoginAction(data: any): any {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    const { cookie } = data.ctx.req.headers
    if (cookie && cookie.indexOf(PublicENV.OAUTH_LOGIN) >= 0) {
      // cookie
      return new Promise((res, rej) => {
        get(OAuth.sessionLogin, {}, {
          headers: {
            cookie
          }
        }).then((data: any) => {
          if (data) {
            dispatch({
              type: OAUTH_SESSION_LOGOUT_TYPE,
              value: data
            })
          }
          res(data)
        }).catch((err) => {
          rej(err)
        })
      })
    }
  }
}

/**
 * 退出登录
 */
export function logout(): (dispatch: Dispatch<AuthActionTypes>) => Promise<AuthActionTypes> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      get(OAuth.logout).then((data: any) => {
        dispatch({
          type: OAUTH_LOGOUT_TYPE,
        })
        res(data)
      }).catch((err) => {
        rej(err)
      })
    })
  }
}

/**
 * 获取QQ用户信息
 */
export function getQQUserInfo(accessToken: string): (dispatch: Dispatch<AuthActionTypes>) => Promise<OAuthStateInterface> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      get(OAuth.qqUserInfo, {
        accessToken
      }).then((data: any) => {
        dispatch({
          type: OAUTH_QQ_USER_INFO_TYPE,
          value: data
        })
        Cookie.set(PublicENV.OAUTH_LOGIN, 'true')
        res(data)
      }).catch((err) => {
        rej(err)
      })
    })
  }
}



